package com.example.test003.controller;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.example.test003.domain.ResponseResult;
import com.example.test003.domain.entity.SysUser;
import com.example.test003.domain.entity.UserPic;
import com.example.test003.domain.vo.LoginVo;
import com.example.test003.domain.vo.UserInfoVo;
import com.example.test003.enums.AppHttpCodeEnum;
import com.example.test003.service.FaceService;
import com.example.test003.utils.BeanCopyUtils;
import com.example.test003.utils.JwtUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
public class FaceController {

    @Autowired
    private FaceService sysUserService;


//    @PostMapping("/face2")
//    public String face2(@RequestBody UserPic userPic) throws IOException {
//        System.out.println(userPic.getPic());
//        return "success";
//    }

    @PostMapping("/faceTest")
    public ResponseResult faceTest(@RequestBody UserPic userPic) throws IOException {
        final String APP_ID = "41860863";
        final String API_KEY = "eGCG6b5sm07YLqXebdtmgcDT";
        final String SECRET_KEY = "XmQcgkMtnrCMvpUWkAktPUcmeiZoN6an";


        //根据用户名向数据库请求人脸照片地址
        SysUser user = sysUserService.getFaceByUsername(userPic.getUsername());

        //得到地址
        System.out.println(user.getFacePic());
        AipFace aipFace = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        //数据库中的人脸照片
        String img1=user.getFacePic();
        String getImageStr1 = GetImageStr(img1);
        String getImageStr2 = userPic.getPic();

        List<MatchRequest> input = new ArrayList<>();
        MatchRequest mr1 = new MatchRequest(getImageStr1, "BASE64");
        MatchRequest mr2 = new MatchRequest(getImageStr2, "BASE64");
        input.add(mr1);
        input.add(mr2);
        JSONObject match = aipFace.match(input);
        System.out.println(match);
        JSONObject result = (JSONObject) match.get("result");
        System.out.println(result);
        String type = result.get("score").getClass().toString();
        System.out.println(type);
        if(type.equals("class java.lang.Double")){
            double score = (double)result.get("score");
            System.out.println(score);
            if (score>50){
                ResponseResult responseResult = login(user);
                return responseResult;
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.VOICE_ERROR);
            }
        }else {
            int score = (int)result.get("score");
            System.out.println(score);
            if (score>50){
                ResponseResult responseResult = login(user);
                return responseResult;
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.VOICE_ERROR);
            }

        }

    }



//    @PostMapping("/face")
//    public String face(@RequestParam("file") MultipartFile file,@RequestParam("username") String  username) throws IOException {
//        final String APP_ID = "41860863";
//        final String API_KEY = "eGCG6b5sm07YLqXebdtmgcDT";
//        final String SECRET_KEY = "XmQcgkMtnrCMvpUWkAktPUcmeiZoN6an";
//
//        //接受来自前端的人脸照片
//        String fileName = file.getOriginalFilename();
//        //保存到某个文件夹
//        String savefile = "C:\\Users\\1\\Desktop\\FACE2\\src\\main\\resources\\images2\\"+fileName;
//        file.transferTo(new File(savefile));
//
//        //根据用户名向数据库请求人脸照片地址
//        SysUser user = sysUserService.getFaceByUsername(username);
//
//        //得到地址
//        System.out.println(user.getFacePic());
//        AipFace aipFace = new AipFace(APP_ID, API_KEY, SECRET_KEY);
//        //数据库中的人脸照片
//        String img1=user.getFacePic();
//        String getImageStr1 = GetImageStr(img1);
//        String getImageStr2 = GetImageStr(savefile);
//
//        List<MatchRequest> input = new ArrayList<>();
//        MatchRequest mr1 = new MatchRequest(getImageStr1, "BASE64");
//        MatchRequest mr2 = new MatchRequest(getImageStr2, "BASE64");
//        input.add(mr1);
//        input.add(mr2);
//        JSONObject match = aipFace.match(input);
//        System.out.println(match);
//        JSONObject result = (JSONObject) match.get("result");
//        System.out.println(result);
//        String type = result.get("score").getClass().toString();
//        System.out.println(type);
//        if(type.equals("class java.lang.Double")){
//            double score = (double)result.get("score");
//            System.out.println(score);
//        }else {
//            int score = (int)result.get("score");
//            System.out.println(score);
//        }
//
//
//        return "success";
//    }

    public static String GetImageStr(String imgFile) {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
    }

    public ResponseResult login(SysUser sysUser){
        String jwt= JwtUtil.createJWT(sysUser.getId().toString());
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(sysUser, UserInfoVo.class);
        LoginVo loginVo = new LoginVo(jwt,userInfoVo);
        return ResponseResult.okResult(loginVo);
    }
}
